<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        title="注意： 只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页部分 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe="stripe">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <!-- 参数名称列 -->
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <!-- 操作列-->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe="stripe">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <!-- 参数名称列 -->
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <!-- 操作列-->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑属性的的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //页面刷新时获取到的分类列表
      cateList: [],
      //级联选择器里面双向绑定的内容
      selectedKeys: [],
      //标签激活页（默认激活第一个标签）
      activeName: 'many',
      //动态参数数据
      manyTableData: [],
      //静态参数数据
      onlyTableData: [],
      //控制添加对话框的显示与隐藏
      addDialogVisible: false,
      //添加表单数据对象
      addForm: {},
      //添加表单对话框的验证规则
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'blur',
          },
        ],
      },
      // 编辑对话框的显示于隐藏
      editDialogVisible: false,
      //编辑对话框的内容绑定
      editForm: {},
      //编辑对话框的预验证
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getCatList()
  },
  methods: {
    async getCatList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status != 200)
        return this.$message.error('获取商品分类失败！')
      this.$message.success('获取商品分类成功！')
      this.cateList = res.data
    },
    // 监听级联选择框中选择的变化
    handleChange() {
      this.getParamsData()
    },
    //监听切换标签
    handleClick() {
      this.getParamsData()
    },
    //获取当前商品的列表数据
    async getParamsData() {
      // 当选中的不是三级分类时
      if (this.selectedKeys.length <= 2) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //   console.log(this.selectedKeys)
      //   console.log(this.catId)
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status != 200)
        return this.$message.error('获取参数列表失败！')
      this.$message.success('获取参数列表成功！ ')
      res.data.forEach((element) => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(' ')
          : []
        element.inputVisible = false
        element.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //监听添加属性对话框的关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //添加属性的确定
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.catId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 201) return this.$message.error('添加参数失败！')
        this.$message.success('添加动态参数/静态属性成功！')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 渲染编辑对话框
    async showEditDialog(info) {
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes/${info.attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      )
      if (res.meta.status != 200) return this.$message.error('获取信息失败！')
      this.$message.success('获取信息成功！')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑对话框的关闭
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮，提交编辑后的内容
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.catId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 200) return this.$message.error('提交信息失败')
        this.$message.success('提交信息成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    async removeParams(info) {
      // 弹框询问是否会删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户确认删除， 返回值是 confirm
      // 如果用户取消删除， 返回值是 cancel
      if (confirmResult != 'confirm') return this.$message.info('已取消删除')
      // console.log('确认删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.catId}/attributes/${info}`
      )
      if (res.meta.status != 200) return this.$message.error('删除失败')
      this.$message.success('删成功！')
      this.getParamsData()
    },
    //展示展开行内输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点
      // $nextTick 作用： 当页面元素被重新渲染之后，才调用$nextTick方法中的回调函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 监听展开行内添加标签的确认
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //提交新添加的标签内容到后台
      this.changeAttrVals(row)
    },
    // attr_vals的修改提交到后台
    async changeAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.catId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status != 200) return this.$message.error('提交标签信息失败')
      this.$message.success('提交标签信息成功！')
    },
    //监听展开行标签关闭事件
    handleClose(index, info) {
      info.attr_vals.splice(index, 1)
      this.changeAttrVals(info)
    },
  },
  computed: {
    // 如果按钮需要被禁用则返回true
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) return true
      return false
    },
    //当前选中的三级分类的id
    catId() {
      if (this.selectedKeys.length == 3) return this.selectedKeys[2]
      else return null
    },
    // 添加属性对话框的标题
    titleText() {
      if (this.activeName == 'many') return '动态参数'
      return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px;
}
.el-tag {
  margin: 5px;
}
.input-tag {
  width: 120px;
}
</style>